#coding:utf-8
__author__ = 'hl'

import wx
import ui.packageui as packageui
import ui.changeDBUI as changeDBUI
import utils.HLMySQLdb as HLMySQLdb
import sys
import utils.operateCache as operateCache
class RedircetPrint:
    def __init__(self,window):
        self.__window = window
    def write(self,str):
        self.__window.AppendText(str)

class MyFrame(wx.Frame):
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id)
        self.createMenuBar()
        self.pkui = packageui.PackagingUI(self,-1)
        self.readDbCache()
        if not self.db:
            self.db = HLMySQLdb.HLMySQLdb()

        self.Bind(wx.EVT_CLOSE,self.OnClose)


    def createMenuBar(self):
        self.CreateStatusBar()
        menubar = wx.MenuBar()
        menu = wx.Menu()
        updateData = menu.Append(-1,u'更新数据',u'更新界面表格中的数据')
        changeConn = menu.Append(-1,u'新建连接',u'修改数据库连接或者新建连接')


        menubar.Append(menu,u'文件')
        self.SetMenuBar(menubar)

        #绑定事件
        self.Bind(wx.EVT_MENU,self.OnChangeConn,changeConn)
        self.Bind(wx.EVT_MENU,self.OnUpdat,updateData)

    def OnChangeConn(self,evt):
        chgDBUI = changeDBUI.ChangeDBUI(self,-1,self.db)
        chgDBUI.ShowModal()

    def OnClose(self,evt):
        self.db.close()
        self.db.conn = None
        self.db.cursor = None
        cache = operateCache.OperateCache('dbCache.txt','w')
        cache.Save(self.db)
        cache.closeFile()
        self.pkui.SaveCache()
        evt.Skip()

    def readDbCache(self):
        cache = operateCache.OperateCache('dbCache.txt','r')
        self.db = cache.Get()
        cache.closeFile()

    def OnUpdat(self,evt):
        #检查数据库是否连接
        if not self.db.isConnect():
            return
        queryChannels = 'select name,encoded from life_platform_type'
        temp = self.db.getData(queryChannels)
        channels =[]
        for channel in temp:
            channels.append(list(channel))
        self.pkui.uiData.updateGridDatas(channels)


if __name__=='__main__':
    app = wx.PySimpleApp()
    frame = MyFrame(None,-1)
    sys.stdout = RedircetPrint(frame.pkui.log)
    frame.Show()
    app.MainLoop()